package com.guiyang.practice.mess1.mapper;

import com.guiyang.practice.mess1.entity.MessageRecord;
import org.apache.ibatis.annotations.*;
import java.util.List;
import java.util.Map;

@Mapper
public interface MessageRecordMapper {

    @Select("SELECT mr.*, mt.type_name FROM message_record mr " +
            "LEFT JOIN message_type mt ON mr.message_type = mt.type_code " +
            "ORDER BY mr.send_time DESC")
    List<MessageRecord> findAll();

    @Select({
            "<script>",
            "SELECT mr.*, mt.type_name FROM message_record mr",
            "LEFT JOIN message_type mt ON mr.message_type = mt.type_code",
            "WHERE 1=1",
            "<if test='title != null and title != \"\"'>",
            "AND mr.title LIKE CONCAT('%', #{title}, '%')",
            "</if>",
            "<if test='messageType != null and messageType != \"\"'>",
            "AND mr.message_type = #{messageType}",
            "</if>",
            "<if test='senderName != null and senderName != \"\"'>",
            "AND mr.sender_name LIKE CONCAT('%', #{senderName}, '%')",
            "</if>",
            "<if test='startTime != null'>",
            "AND mr.send_time &gt;= #{startTime}",
            "</if>",
            "<if test='endTime != null'>",
            "AND mr.send_time &lt;= #{endTime}",
            "</if>",
            "ORDER BY mr.send_time DESC",
            "</script>"
    })
    List<MessageRecord> findByCondition(Map<String, Object> params);

    @Select("SELECT COUNT(*) FROM message_record WHERE message_type = #{typeCode}")
    int countByType(String typeCode);

    @Insert("INSERT INTO message_record(title, content, message_type, sender_id, " +
            "sender_name, receiver_type, receiver_ids, send_time, status, create_time) " +
            "VALUES(#{title}, #{content}, #{messageType}, #{senderId}, " +
            "#{senderName}, #{receiverType}, #{receiverIds}, #{sendTime}, #{status}, #{createTime})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(MessageRecord messageRecord);

    @Select("SELECT mr.*, mt.type_name FROM message_record mr " +
            "LEFT JOIN message_type mt ON mr.message_type = mt.type_code " +
            "WHERE mr.id = #{id}")
    MessageRecord findById(Long id);

    @Update("UPDATE message_record SET status = #{status} WHERE id = #{id}")
    int updateStatus(@Param("id") Long id, @Param("status") Integer status);

    @Update("UPDATE message_record SET " +
            "title = #{title}, " +
            "content = #{content}, " +
            "message_type = #{messageType}, " +
            "receiver_type = #{receiverType}, " +
            "receiver_ids = #{receiverIds}, " +
            "status = #{status} " +
            "WHERE id = #{id}")
    int update(MessageRecord messageRecord);
}